package com.example.enterprise.config;

import com.example.enterprise.task.MySecondJob;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.SimpleTrigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.*;

//@Configuration
public class QuartzConfig {
    /**
     * Quartz的核心1：jobDetail----炸药
     * @return
     */
    @Bean
    MethodInvokingJobDetailFactoryBean jobDetail() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myFirstJob");//指定bean名称
        bean.setTargetMethod("sayHello");//bean中定时执行的方法名
        return bean;
    }
    @Bean
    JobDetailFactoryBean jobDetail2() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MySecondJob.class);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("name", "kate-chan");
        bean.setJobDataMap(jobDataMap);
        /**指定作业的持久性，即即使不再有触发器指向它，它是否仍应存储在作业存储中。*/
        bean.setDurability(true);
        return bean;
    }

    /**
     *  Quartz的核心2：Trigger-----引线
     */
    @Bean
    SimpleTriggerFactoryBean simpleTrigger() {
        SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
        bean.setJobDetail(jobDetail().getObject());
        bean.setRepeatCount(3);//任务循环次数
        bean.setStartDelay(1000); //配置任务启动延迟时间
        bean.setRepeatInterval(2000);  //配置任务的时间间隔
        return bean;
    }

    @Bean
    CronTriggerFactoryBean cronTrigger() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(jobDetail2().getObject());
        bean.setCronExpression("0/5 * * * * ?");
        return bean;
    }
    /**
     *  Quartz的核心3：SchedulerFactory------点火的人
     */
    @Bean
    SchedulerFactoryBean schedulerFactory() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        SimpleTrigger simpleTrigger = simpleTrigger().getObject();

        CronTrigger cronTrigger = cronTrigger().getObject();
        bean.setTriggers(simpleTrigger,cronTrigger);
        return bean;
    }
}
